package top.lyjwn.todo.common.utils.http;

import java.io.*;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author luoyujie
 */
public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public final static String METHOD_GET = "GET";

    public final static String METHOD_POST = "POST";

    /**
     * get或者post请求
     *
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String request(String requestUrl, String requestMethod, String outputStr) {
        Map<String, String> requestProperty = new HashMap<>();
        requestProperty.put("Content-Type", "text/xml;charset=utf-8");
        return request(requestUrl, requestProperty, requestMethod, outputStr);
    }

    /**
     * get或者post请求
     *
     * @param requestUrl
     * @param requestProperty
     * @param requestMethod   GET or POST 需要大写
     * @param outputStr
     * @return
     * @author luoyujie
     */
    public static String request(String requestUrl, Map<String, String> requestProperty, String requestMethod, String outputStr) {
        StringBuilder buffer = new StringBuilder();
        HttpURLConnection httpUrlConn = null;
        try {

            URL url = new URL(requestUrl);
            if (requestUrl.toLowerCase().contains("https://")) {
                // 创建SSLContext对象，并使用我们指定的信任管理器初始化
                TrustManager[] tm = {new I509TrustManager()};
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());
                // 从上述SSLContext对象中得到SSLSocketFactory对象
                SSLSocketFactory ssf = sslContext.getSocketFactory();
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                httpsURLConnection.setSSLSocketFactory(ssf);
                httpUrlConn = httpsURLConnection;
            } else {
                httpUrlConn = (HttpURLConnection) url.openConnection();
            }
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            //httpUrlConn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            for (Map.Entry<String, String> stringStringEntry : requestProperty.entrySet()) {
                httpUrlConn.setRequestProperty(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            if (METHOD_GET.equalsIgnoreCase(requestMethod)) httpUrlConn.connect();
            // 当有数据需要提交时
            if (null != outputStr) {
                try (OutputStream outputStream = httpUrlConn.getOutputStream();) {
                    // 注意编码格式，防止中文乱码
                    outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
                    outputStream.close();
                }

            }
            // 将返回的输入流转换成字符串
            try (InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                // 释放资源
                inputStream.close();
            }

        } catch (ConnectException ce) {
            logger.error("connection timed out.", ce);
            return null;
        } catch (Exception e) {
            logger.error("https request error", e);
            return null;
        } finally {
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }
        return buffer.toString();
    }

    /**
     * get或者post请求
     *
     * @param requestUrl
     * @param requestMethod GET or POST 需要大写
     * @return
     * @author luoyujie
     */

    public static String request(String requestUrl, String requestMethod) {
        return request(requestUrl, requestMethod, null);
    }


    /**
     * 下载文件
     * @param httpUrl
     * @return
     */
    public static byte[] downloadFileAsByteArray(String httpUrl) {
        try (HttpClient client = HttpClient.newHttpClient()) {
            HttpRequest request = HttpRequest.newBuilder().uri(URI.create(httpUrl)).GET() // 可以根据需要修改为POST、PUT等
                    .build();
            HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
            if (response.statusCode() == 200) {
                return response.body();
            } else {
                logger.error("下载文件失败，状态码：" + response.statusCode());
            }
        } catch (Exception e) {
            logger.error("下载文件时出现错误：", e);
        }
        return null;
    }

}
